/**
 * 
 */
package com.lanswon.controller;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lanswon.common.constants.Constants;
import com.lanswon.common.enums.MessageType;
import com.lanswon.common.enums.UserType;
import com.lanswon.common.util.StringUtil;
import com.lanswon.entity.UserVO;
import com.lanswon.entity.Verification;
import com.lanswon.service.AdminService;
import com.lanswon.service.UserService;
import com.lanswon.service.VerificationService;

/**
 * @author lanswon
 *
 */
@Controller
@RequestMapping("/front/user")
public class UserController {
	@Autowired
	UserService userService;
	@Autowired
	AdminService adminService;
	@Autowired
	VerificationService verificationService;
	
	/**  
	 * zj
	* @Title: delUserInfo
	* @Description: TODO(用户信息注销)
	* @param @param userPhone
	* @param @param verifyCode
	* @param @return
	*
	*/
	@RequestMapping("/delUserInfo")
	@ResponseBody
	public Map<String, Object> delUserInfo(HttpServletRequest request,
			String userPhone,String verifyCode){
		Map<String, Object> viewMap = new HashMap<>();
		try {
			if(StringUtil.isEmpty(userPhone)){
				viewMap.put("code", 1);
				viewMap.put("message", "手机号不能为空");
				return viewMap;
			}
			Long userId = (Long) request.getSession().getAttribute("userId");
			// 登陆校验
			if (userId == null) {
				viewMap.put("code", 2);
				viewMap.put("message", MessageType.MT012);
				return viewMap;
			}
			/*String passwordCode = (String) request.getSession().getAttribute("verifyCode");
			if(StringUtil.isEmpty(verifyCode)||!verifyCode.equals(passwordCode)){
				viewMap.put("code", 3);
				viewMap.put("message", "验证码不正确");
				return viewMap;
			}*/
			Verification verification = verificationService.findVerificationByPhone(userPhone);
			Long time = new Date().getTime();
			if((time.longValue()-verification.getVerifytime().longValue())/1000>60){
				viewMap.put("code", 4);
				viewMap.put("message", "验证码过期");
				return viewMap;
			}
			if(StringUtil.isEmpty(verification.getVerifycode())||!verifyCode.equals(verification.getVerifycode())){
				viewMap.put("code", 3);
				viewMap.put("message", "验证码错误");
				return viewMap;
			}
			UserVO userVO = userService.findUserByMobile(userPhone);
			if(userVO==null){
				viewMap.put("code", 4);
				viewMap.put("message", "用户不存在");
				return viewMap;
			}
			request.getSession().removeAttribute("userId");
			request.getSession().removeAttribute("userName");
			userService.delUserInfo(userPhone);
			viewMap.put("code", 0);
			viewMap.put("message", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "删除失败");
		}
		return viewMap;
	}
	
	/**  
	* @Title: logout
	* @Description: TODO(退出登录)
	* @param @param request
	* @param @return
	*
	*/
	@RequestMapping("/logout")
	@ResponseBody
	public Map<String, Object> logout(HttpServletRequest request){
		Map<String, Object> viewMap = new HashMap<>();
		try {
			request.getSession().removeAttribute("userId");
			request.getSession().removeAttribute("userName");
			viewMap.put("code", 0);
			viewMap.put("message", "退出成功");
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "退出失败");
		}
		return viewMap;
	}
	
	/**  
	* (忘记密码)
	*/
	@RequestMapping("/forgetPassword")
	@ResponseBody
	public Map<String, Object> forgetPassword(HttpServletRequest request,String phone,
			String verifyCode,String password,String confirmPassword) throws IOException {
		Map<String, Object> viewMap = new HashMap<>();
		
		try {
			if(StringUtil.isEmpty(phone)||StringUtil.isEmpty(verifyCode)||StringUtil.isEmpty(password)
					||StringUtil.isEmpty(confirmPassword)){
				viewMap.put("code", 1);
				viewMap.put("message", "参数不能为空");
				return viewMap;
			}
			if(!password.equals(confirmPassword)){
				viewMap.put("code", 2);
				viewMap.put("message", "密码不一致");
				return viewMap;
			}
			Verification verification = verificationService.findVerificationByPhone(phone);
			Long time = new Date().getTime();
			if((time.longValue()-verification.getVerifytime().longValue())/1000>60){
				viewMap.put("code", 3);
				viewMap.put("message", "验证码过期");
				return viewMap;
			}
			if(StringUtil.isEmpty(verification.getVerifycode())||!verifyCode.equals(verification.getVerifycode())){
				viewMap.put("code", 4);
				viewMap.put("message", "验证码错误");
				return viewMap;
			}
			userService.forgetPassword(phone,password);
			viewMap.put("code", 0);
			viewMap.put("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "操作失败");
		}
		return viewMap;
	}
	
	
	/**  
	* @Title: validate
	* @Description: TODO(注册)
	* @param @param request
	* @param @return
	*
	*/
	@RequestMapping("/validate")
	@ResponseBody
	public Map<String, Object> validate(HttpServletRequest request) {
		return userService.validateCode(request,Constants.SMS_UPDATEP_ASSWORD);
	}

	@RequestMapping("/checkUserName")
	@ResponseBody
	public Map<String, Object> checkUserName(String userName) {
		return userService.checkUserName(userName);
	}
	
	
	@RequestMapping("/grsz")
	@ResponseBody
	public Map<String, Object> grsz(HttpServletRequest request) {
		Map<String, Object> viewMap = new HashMap<>();
		try {
			Long userId = (Long) request.getSession().getAttribute("userId");
			if(userId==null){
				viewMap.put("code", 1);
				viewMap.put("message", "未登录");
				return viewMap;
			}
			UserVO user = userService.getUser(userId);
			viewMap.put("code", 0);
			viewMap.put("data", user);
			viewMap.put("message", "请求成功");
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "请求失败");
		}
		return viewMap;
	}
	
	
	

	@RequestMapping("/checkEmail")
	@ResponseBody
	public Map<String, Object> checkEmail(String email) {
		return userService.checkEmail(email);
	}

	@RequestMapping("/checkPhone")
	@ResponseBody
	public Map<String, Object> checkPhone(String phone) {
		return userService.checkPhone(phone);
	}
	
	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> login(HttpServletRequest request,String phone,String password) {
		Map<String, Object> viewMap = new HashMap<>();
		try {
			if(StringUtil.isEmpty(phone)||StringUtil.isEmpty(password)||!StringUtil.isMobile(phone)){
				viewMap.put("code", 1);
				viewMap.put("message", "用户名密码不正确");
				return viewMap;
			}
			//UserVO user = userService.findUserByNameOrPassword(phone,StringUtil.md5(password));
			UserVO user = userService.findUserByMobile(phone);
			if(user==null){
				viewMap.put("code", 2);
				viewMap.put("message", "该用户未注册");
				return viewMap;
			}
			String md5password = StringUtil.md5(password);
			if(!md5password.equals(user.getPassword())){
				viewMap.put("code", 3);
				viewMap.put("message", "密码不正确");
				return viewMap;
			}
			request.getSession().setAttribute("userId", user.getUserId());
			request.getSession().setAttribute("isLogin", "1");
			Map<String, Object> data = new HashMap<>();
			Class<? extends UserVO> clazz = user.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
			    field.setAccessible(true);
			    data.put(field.getName(), field.get(user));
			}
			request.getSession().setAttribute("userName", data.get("userName"));
			request.getSession().setAttribute("idNum", data.get("idNum"));
			request.getSession().setAttribute("realName", data.get("realName"));
			request.getSession().setAttribute("email", data.get("email"));
			viewMap.put("code", 0);
			viewMap.put("message", "登录成功");
			viewMap.put("data", data);
		} catch ( Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "登录失败");
		}
		return viewMap;
	}
	
	/*@RequestMapping("/isLogin")
	@ResponseBody
	public Map<String, Object> isLogin(HttpServletRequest request) {
		Map<String, Object> viewMap = new HashMap<>();
		request.getSession().
		viewMap.put("code", 0);
		viewMap.put("message", "请求成功");
		viewMap.put("data", data);
		return 
	}*/
	

	@RequestMapping("/register")
	@ResponseBody
	public Map<String, Object> doRegister(HttpServletRequest request,String verifyCode,
			String password,String confirmPassword,String phone) {
		Map<String, Object> viewMap = new HashMap<>();
		try {
			// 参数验证
			if (StringUtil.isEmpty(password) || StringUtil.isEmpty(confirmPassword)
					|| StringUtil.isEmpty(phone) || StringUtil.isEmpty(verifyCode)) {
				viewMap.put("code", 1);
				viewMap.put("message", "参数异常");
				return viewMap;
			}
			if(!password.equals(confirmPassword)){
				viewMap.put("code", 2);
				viewMap.put("message", "密码与确认密码不一致");
				return viewMap;
			}
			if(!StringUtil.containAlphanumeric(password)&&password.length()<8){
				viewMap.put("code", 3);
				viewMap.put("message", "密码必须包含字母和数字并且长度不能小于8");
				return viewMap;
			}
			/*String sessionCode = (String) request.getSession().getAttribute("verifyCode");
			if(StringUtil.isEmpty(sessionCode)||!verifyCode.equals(sessionCode)){
				viewMap.put("code", 4);
				viewMap.put("message", "验证码错误");
				return viewMap;
			}*/
			Verification verification = verificationService.findVerificationByPhone(phone);
			Long time = new Date().getTime();
			if((time.longValue()-verification.getVerifytime().longValue())/1000>60){
				viewMap.put("code", 4);
				viewMap.put("message", "验证码过期");
				return viewMap;
			}
			if(StringUtil.isEmpty(verification.getVerifycode())||!verifyCode.equals(verification.getVerifycode())){
				viewMap.put("code", 3);
				viewMap.put("message", "验证码错误");
				return viewMap;
			}
			
			UserVO userVO = userService.findUserByMobile(phone);
			if(userVO!=null){
				viewMap.put("code", 5);
				viewMap.put("message", "该用户已被注册");
				return viewMap;
			}
			
			UserVO user = new UserVO();
			user.setMobile(phone);
			user.setUserName(phone);
			user.setPassword(StringUtil.md5(password));
			user.setUserType(UserType.UT002.getCode().byteValue());
			userService.addUser(user);
			Map<String, Object> data = new HashMap<>();
			Class<? extends UserVO> clazz = user.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
			    field.setAccessible(true);
			    data.put(field.getName(), field.get(user));
			}
			viewMap.put("code", 0);
			viewMap.put("data", data);
			viewMap.put("message", "请求成功");
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "请求失败");
		}
		//userService.updateTokenById(userService.doRegister(request));
		return viewMap;
	}

	
	/**  
	* @Title: updateUserInfo
	* @Description: TODO(修改个人信息)
	* @param @param request
	* @param @param token
	* @param @param realName
	* @param @param idNum
	* @param @param birthday
	* @param @param verifyCode
	* @param @return
	*
	*/
	@RequestMapping("/updateUserInfo")
	@ResponseBody
	public Map<String, Object> updateUserInfo(HttpServletRequest request,
			String realName,String idNum,String birthday,String verifyCode,String email) {
		Map<String, Object> viewMap = new HashMap<>();
		try {
			HttpSession session = request.getSession();
			Long userId = (Long) session.getAttribute("userId");
			if(StringUtil.isEmpty(realName)||StringUtil.isEmpty(idNum)||
					StringUtil.isEmpty(birthday)||StringUtil.isEmpty(verifyCode)){
				viewMap.put("code", 1);
				viewMap.put("message", "参数不能为空");
				return viewMap;
			}
			if(!StringUtil.isIdNum(idNum)){
				viewMap.put("code", 2);
				viewMap.put("message", "身份证填写错误");
				return viewMap;
			}
			if(!StringUtil.isDate(birthday)){
				viewMap.put("code", 3);
				viewMap.put("message", "生日填写不正确");
				return viewMap;
			}
			String sessionCode = (String) session.getAttribute("verifyCode");
			if(!sessionCode.equals(verifyCode)){
				viewMap.put("code", 4);
				viewMap.put("message", "验证码不正确");
				return viewMap;
			}
			if(userId==null){
				viewMap.put("code", 5);
				viewMap.put("message", "您还未登录，不能做此操作");
				return viewMap;
			}
			UserVO userVO2 = userService.getUserByIdNo(idNum);
			if(userVO2!=null){
				viewMap.put("code", 7);
				viewMap.put("message", "该证件号已被绑定");
				return viewMap;
			}
			UserVO user = new UserVO();
			user.setUserId(userId);
			user.setRealName(realName);
			user.setIdNum(idNum);
			user.setPapertype("00");
			user.setPaperno(idNum);
			user.setBirthday(birthday);
			user.setEmail(email);
			userService.updateUserInfo(user);
			Map<Object, Object> dataMap = new HashMap<>();
			request.getSession().setAttribute("realName", realName);
			request.getSession().setAttribute("idNum", idNum);
			request.getSession().setAttribute("email", email);
			dataMap.put("realName", realName);
			dataMap.put("idNum", idNum);
			dataMap.put("birthday", birthday);
			viewMap.put("data", dataMap);
			viewMap.put("code", 0);
			viewMap.put("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "修改失败");
		}
		
		//adminService.withdraw(request);		
		return viewMap;

	}
	
	/**  
	* @Title: updateUserInfo
	* @Description: TODO(修改个人信息)
	* @param @param request
	* @param @param token
	* @param @param realName
	* @param @param idNum
	* @param @param birthday
	* @param @param verifyCode
	* @param @return
	*
	*/
	@RequestMapping("/setUserInfo")
	@ResponseBody
	public Map<String, Object> setUserInfo(HttpServletRequest request,
			String realName,String idNum,String birthday,String email) {
		Map<String, Object> viewMap = new HashMap<>();
		try {
			HttpSession session = request.getSession();
			Long userId = (Long) session.getAttribute("userId");
			if(StringUtil.isEmpty(realName)||StringUtil.isEmpty(idNum)||
					StringUtil.isEmpty(birthday)){
				viewMap.put("code", 1);
				viewMap.put("message", "参数不能为空");
				return viewMap;
			}
			if(!StringUtil.isIdNum(idNum)){
				viewMap.put("code", 2);
				viewMap.put("message", "身份证填写错误");
				return viewMap;
			}
			if(!StringUtil.isDate(birthday)){
				viewMap.put("code", 3);
				viewMap.put("message", "生日填写不正确");
				return viewMap;
			}
			if(userId==null){
				viewMap.put("code", 5);
				viewMap.put("message", "您还未登录，不能做此操作");
				return viewMap;
			}
			UserVO user = new UserVO();
			user.setUserId(userId);
			user.setRealName(realName);
			user.setIdNum(idNum);
			user.setBirthday(birthday);
			user.setEmail(email);
			userService.updateUserInfo(user);
			Map<Object, Object> dataMap = new HashMap<>();
			request.getSession().setAttribute("realName", realName);
			request.getSession().setAttribute("idNum", idNum);
			request.getSession().setAttribute("email", email);
			viewMap.put("data", dataMap);
			viewMap.put("code", 0);
			viewMap.put("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "操作错误");
		}
		
		//adminService.withdraw(request);		
		return viewMap;

	}
	
	/**  
	* @Title: sendPWValidate
	* @Description: TODO(修改密码)
	* @param @param request
	* @param @return
	*
	*/
	/*@RequestMapping("/sendPWValidate")
	@ResponseBody
	public Map<String, Object> sendPWValidate(HttpServletRequest request) {
		return userService.sendPWValidate(request);
	}*/

	@RequestMapping("/changeValidate")
	@ResponseBody
	public Map<String, Object> changeValidate(HttpServletRequest request,String phone,
			String verifyCode,String newPassword) {
		Map<String, Object> viewMap = new HashMap<>();
		try {
			if(StringUtil.isEmpty(phone)||StringUtil.isEmpty(verifyCode)||StringUtil.isEmpty(newPassword)){
				viewMap.put("code", 1);
				viewMap.put("message", "用户名密码不能为空");
				return viewMap;
			}
			String sessionCode = (String) request.getSession().getAttribute("verifyCode");
			if(!verifyCode.equals(sessionCode)){
				viewMap.put("code", 3);
				viewMap.put("message", "验证码错误");
				return viewMap;
			}
			userService.forgetPassword(phone,newPassword);
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("code", 99);
			viewMap.put("message", "操作有误");
		}
		
		return viewMap;
	}
	
	@RequestMapping("/userCardBind")
	@ResponseBody
	public Map<String, Object> userCardBind(HttpServletRequest request, String cardType, String cardNo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			//验证信息是否完善
			Long userId = (Long) request.getSession().getAttribute("userId");
			if(StringUtil.isEmpty(cardType)||StringUtil.isEmpty(cardNo)){
				resultMap.put("code", 1);
				resultMap.put("message", "证件号信息不能空");
				return resultMap;
			}
			// 登陆校验
			if (userId == null) {
				resultMap.put("code", 2);
				resultMap.put("message", MessageType.MT012);
				return resultMap;
			}
			UserVO user = userService.getUser(userId);
			if(user==null){
				resultMap.put("code", 3);
				resultMap.put("message", "用户不存在或未登录");
				return resultMap;
			}
			String[] cardNos = {cardNo};
			resultMap = userService.bind(user, cardNos);
			
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", 99);
			resultMap.put("message", "绑定失败");
		}
		
		return resultMap;
	}
	
	
	/*@RequestMapping("/bind")
	@ResponseBody
	public Map<String, Object> bind(HttpServletRequest request, String paperType, String[] paperNo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			//验证信息是否完善
			Long userId = (Long) request.getSession().getAttribute("userId");
			if(StringUtil.isEmpty(paperType)||StringUtil.isEmpty(paperNo)){
				resultMap.put("code", 1);
				resultMap.put("message", "证件号信息不能空");
				return resultMap;
			}
			// 登陆校验
			if (userId == null) {
				resultMap.put("code", 2);
				resultMap.put("message", MessageType.MT012);
				return resultMap;
			}
			UserVO user = userService.getUser(userId);
			if(user==null){
				resultMap.put("code", 3);
				resultMap.put("message", "用户不存在或未登录");
				return resultMap;
			}
			if(!StringUtil.isEmpty(user.getPaperno())&&!StringUtil.isEmpty(user.getPapertype())){
				if(user.getPaperno().equals(paperNo)&&user.getPapertype().equals(paperType)){
				}else{
					resultMap.put("code", 4);
					resultMap.put("message", "证件号和证件类型填写错误");
					return resultMap;
				}
			}else{
				user.setPaperno(paperNo);
				user.setPapertype(paperType);
			}
			resultMap = userService.bind(user, paperNo);
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", 99);
			resultMap.put("message", "绑定失败");
		}
		
		return resultMap;
	}*/
	
	
	

	/*@RequestMapping("/changePassword")
	@ResponseBody
	public Map<String, Object> changePassword(HttpServletRequest request,String oldPassword,String newPassword) {
		Map<String, Object> dataMap = new HashMap<>();
		// 登陆校验
		Long userId = (Long) request.getSession().getAttribute("userId");
		if (userId == null) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT012);
			return dataMap;
		}	
		// 传参校验
		if (StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_SR_3);
			return dataMap;
		}
		return userService.changePassword(userId,oldPassword,newPassword);
	}*/
}
